#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@version: ??
@author: happiness
@license: Apache Licence 
@contact: happiness_ws@163.com
@site: 
@software: PyCharm
@file: mnist.py
@time: 2017/11/6 13:07
@content:手写体识别,只有一个隐藏层，10个输出
"""

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data

# 输入节点数
INPUT_NODE = 28 * 28
# 输出节点数
OUTPUT_NODE = 10

# 隐藏层节点数
LAYER1_NODE = 500

# 一个训练batch的大小
BATCH_SIZE = 100

# 初始学习率
LEARNING_RATE_BASE = 0.8
# 学习率衰减率
LEARNING_RATE_DECAY = 0.98

# 正则化在损失函数的系数
REGULARIZATION_RATE = 0.001

# 训练轮数
TRAINING_STEPS = 5000

# 移动平均衰减系数
MA_DECAY = 0.99


def inference(input_tensor, avg_class, weight1, biases1, weight2, biases2):
    '''
    创建神经网络，只有一个隐藏层，使用ReLU去线性化
    :param input_tensor: 输入张量
    :param avg_class: 移动平均
    :param weight1: 输入层权值
    :param biases1: 输入层偏置
    :param weight2: 隐藏层到输出层的权值
    :param biases2: 隐藏层到输出层的偏置
    :return: 前向神经网络
    '''
    if avg_class == None:
        # 不使用移动平均指数
        layer1 = tf.nn.relu(tf.matmul(input_tensor, weight1) + biases1)
        return tf.matmul(layer1, weight2) + biases2
    else:
        # 使用移动平均指数
        layer1 = tf.nn.relu(tf.matmul(input_tensor, avg_class.average(weight1)) + avg_class.average(biases1))
        return tf.matmul(layer1, avg_class.average(weight2)) + avg_class.average(biases2)


def train(mnist):
    '''
    训练数据
    :param mnist:mnist数据集
    :return:
    '''
    # 创建输入变量
    x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
    x = tf.nn.dropout(x, keep_prob=0.5)
    y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')

    # 生成隐藏层权值参数
    weight1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))
    biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))

    # 生成输出层参数
    weight2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
    biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))

    # 创建前向神经网络
    y = inference(x, None, weight1, biases1, weight2, biases2)

    # 定义移动平均类
    globalStep = tf.Variable(0, trainable=False)
    variable_ma = tf.train.ExponentialMovingAverage(MA_DECAY, globalStep)
    variable_ma_op = variable_ma.apply(tf.trainable_variables())
    ma_y = inference(x, variable_ma, weight1, biases1, weight2, biases2)

    # 创建损失函数
    loss_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y_, 1), logits=y)
    loss_entropy_mean = tf.reduce_mean(loss_entropy)

    # 使用L2正则化
    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)

    regularization = regularizer(weight1) + regularizer(weight2)

    loss = loss_entropy_mean + regularization

    # decay_steps = mnist.train.num_examples / BATCH_SIZE

    # 创建使用指数衰减的学习率

    decay_learing_reate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step=globalStep,
                                                     decay_steps=int(mnist.train.num_examples / BATCH_SIZE),
                                                     decay_rate=LEARNING_RATE_DECAY, staircase=True)

    train_step = tf.train.GradientDescentOptimizer(decay_learing_reate).minimize(loss=loss,
                                                                                 global_step=globalStep)

    # 反向传播更新参数
    with tf.control_dependencies([train_step, variable_ma_op]):
        train_op = tf.no_op("train")

    # 计算正确率
    correct_prediction = tf.equal(tf.argmax(ma_y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
        test_feed = {x: mnist.test.images, y_: mnist.test.labels}

        for i in range(TRAINING_STEPS):
            if i % 1000 == 0:
                validate_acc = sess.run(accuracy, feed_dict=validate_feed)
                print("After %d training step(s), validation accuracy using average model is %g " % (i, validate_acc))

            xs, ys = mnist.train.next_batch(BATCH_SIZE)
            sess.run(train_op, feed_dict={x: xs, y_: ys})

        test_acc = sess.run(accuracy, feed_dict=test_feed)
        print("After %d training step(s), validation accuracy using average model is %g " % (TRAINING_STEPS, test_acc))


if __name__ == '__main__':
    # 加载mnist数据集
    mnist = input_data.read_data_sets('/MNIST_DATA/', one_hot=True)
    train(mnist)
